﻿using Microsoft.Extensions.Caching.Memory;

namespace Sage.Caching.Memory.Extensions
{
    /// <summary>
    /// 为 MemoryCacheEntryOptions 提供扩展方法。
    /// </summary>
    public static class MemoryCacheEntryOptionsExtensions
    {
        /// <summary>
        /// 创建 MemoryCacheEntryOptions 的克隆副本。
        /// </summary>
        /// <param name="options">要克隆的选项对象。</param>
        /// <returns>新的 MemoryCacheEntryOptions 实例。</returns>
        public static MemoryCacheEntryOptions Clone(this MemoryCacheEntryOptions options)
        {
            ArgumentNullException.ThrowIfNull(options);

            var clone = new MemoryCacheEntryOptions
            {
                AbsoluteExpiration = options.AbsoluteExpiration,
                AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow,
                SlidingExpiration = options.SlidingExpiration,
                Priority = options.Priority,
                Size = options.Size
            };

            // 复制回调
            foreach (var callback in options.PostEvictionCallbacks)
            {
                // 添加 null 检查或使用 null 断言运算符
                if (callback.EvictionCallback != null)
                {
                    clone.RegisterPostEvictionCallback(callback.EvictionCallback, callback.State);
                }
                // 或者使用 null 断言运算符：
                // clone.RegisterPostEvictionCallback(callback.EvictionCallback!, callback.State);
            }

            return clone;
        }
    }
}
